package ThreadPoolExecutors;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadFactory;

/**
 * Created with IntelliJ IDEA
 * Description:线程池模拟实现
 * User:34398
 * Date:2024-07-26
 * Time:14:34
 */
//
//class SimpleThreadFactory implements ThreadFactory {
//    public Thread newThread(Runnable r) {
//        return new Thread(r);
//    }
//}

class MyThreadPool{


    //设置任务队列（阻塞队列）
    private BlockingQueue<Runnable> blockingQueue=new ArrayBlockingQueue<Runnable>(1000);

    //创建一个几个线程？
    public MyThreadPool(int capacity){

        for (int i = 0; i <capacity ; i++) {
            Thread t=new Thread(()->{
                while(true){
                    try {
                        Runnable r=blockingQueue.take();
                        r.run();//执行任务队列中的任务
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            });
            t.start();//启动线程
        }
    }

    //添加任务
    public void submit(Runnable runnable) throws InterruptedException {

        //把任务放到任务队列中
        blockingQueue.put(runnable);

    }
}


public class Demo {
    public static void main(String[] args) throws InterruptedException {
            MyThreadPool myThreadPool=new MyThreadPool(4);
        for (int i = 0; i <1000 ; i++) {
            int id=i;
            myThreadPool.submit(()->{
                Thread cur=Thread.currentThread();
                System.out.println("任务："+id+","+cur.getName());
            });
        }
    }
}







